package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ProfileStationListActivity extends ListActivity{
	private ImageButton favorite, talk, board;
	private ArrayList<JSONObject> json_list;
	private ArrayList<StationItem> list;
	private StationItemAdapter adapter;
	private String user_id, check;
	private ImageView back;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.profile_station);
	    list = new ArrayList<StationItem>();
	    json_list = new ArrayList<JSONObject>();
	    favorite = (ImageButton)findViewById(R.id.btnFavorite);
	    talk = (ImageButton)findViewById(R.id.btnTalk);
	    board = (ImageButton)findViewById(R.id.btnBoard);
	    back = (ImageView)findViewById(R.id.btnBack);
	    setClickListener();
	    Intent intent = getIntent();
		user_id = intent.getExtras().get("user_id").toString();
	    check = intent.getExtras().get("check").toString();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.userName, "user_id", user_id, "mUser_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			JSONArray title_Result;
			try{
				title_Result = new JSONArray(result);
				JSONObject titleObject = (JSONObject) title_Result.get(0);
				TextView title = (TextView)findViewById(R.id.title);
				title.setText(titleObject.get("nick_name").toString());
				
				DownloadListAsynkTask task2 = new DownloadListAsynkTask();
				String[] params = new String[]{ ServerURL.stationFromUser , "user_id", user_id, "mUser_id", Preferences.getValue(getBaseContext(), "user_id")};
				task2.execute(params);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	private class DownloadListAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			JSONObject json_result;
			ArrayList<String> favorite_list = new ArrayList<String>();;
			json_list.clear();
			list.clear();
			favorite_list.clear();
			try{
				json_result = new JSONObject(result);
				JSONArray json_favorite_list = json_result.getJSONArray("favorite_list");
				JSONArray json_station_list = json_result.getJSONArray("station_list");
				
				for(int i = 0 ; i < json_station_list.length(); i++){
					JSONObject json_obj = (JSONObject) json_station_list.get(i);
					json_list.add(json_obj);
				}
				Collections.sort(json_list, myComparator);
				
				for(int i = 0 ; i < json_favorite_list.length(); i++){
					JSONObject json_obj = (JSONObject) json_favorite_list.get(i);
					favorite_list.add(json_obj.getString("station_id"));
				}
				
				for(int i = 0 ; i < json_list.size() ; i++){
					String stationName = (String)json_list.get(i).get("name");
					String stationId = json_list.get(i).get("station_id").toString();
					StationItem eachItem = new StationItem(stationId.toString(), stationName);
					
					if(favorite_list.contains(stationId)){
						eachItem.setIconId(R.drawable.btn_remove);
					}
					else{
						eachItem.setIconId(R.drawable.btn_add);
					}
					list.add(eachItem);
				}
				adapter = new StationItemAdapter(getBaseContext(), R.layout.list_row, list);
			    ListView lv = getListView();
			    lv.setAdapter(adapter);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	private class favoriteAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("favorite")){
				Toast.makeText(getBaseContext(), "친구로 등록하였습니다.", Toast.LENGTH_SHORT).show();
				check = result;
			}
			else if(result.equals("deny")){
				Toast.makeText(getBaseContext(), "차단되었습니다.", Toast.LENGTH_SHORT).show();
				check = result;
			}
		}
	}

	private class MakeTalkAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
		        JSONObject resultData = new JSONObject(result);
		        String roomId = resultData.getString("room_id");
		        Intent chatIntent = new Intent(getBaseContext(), ChatRoomActivity.class);
				chatIntent.putExtra("roomId", roomId);
				chatIntent.putExtra("isChat", true);
				startActivity(chatIntent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
		}
	}
    private final static Comparator<JSONObject> myComparator= new Comparator<JSONObject>() {
        private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
        	try {
				return collator.compare(object1.get("name"), object2.get("name"));
			} catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
		}
    };

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		StationItem selectedItem = (StationItem) parent.getItemAtPosition(position);
		UploadAsynkTask task = new UploadAsynkTask();
		String[] params;
		if(selectedItem.getIconId() == R.drawable.btn_remove){
//			Toast.makeText(getBaseContext(), "이미 추가했습니다", Toast.LENGTH_SHORT).show();
			params = new String[]{ServerURL.deleteFavorieteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "station_id", selectedItem.getStationId()};
			list.get(position).setIconId(R.drawable.btn_add);
		}
		else{
			params = new String[]{ServerURL.addFavoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "station_id", selectedItem.getStationId()};
			list.get(position).setIconId(R.drawable.btn_remove);
		}
		task.execute(params);
	}
	
	public void setClickListener(){
		back.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		talk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				List<String> chatRoomUsers = new ArrayList<String>();
				chatRoomUsers.add(user_id);
				chatRoomUsers.add(Preferences.getValue(getBaseContext(), "user_id"));
				
				MakeTalkAsynkTask task = new MakeTalkAsynkTask();
				String[] params = new String[]{ ServerURL.createRoom, 
									"json_string", chatRoomUsers.toString(),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		favorite.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String url = "";
				if(check.equals("none")){
					url = ServerURL.moveToFavorite;
				}
				else if(check.equals("favorite")){
					url = ServerURL.moveFavoriteToDeny;
				}
				else if(check.equals("deny")){
					url = ServerURL.moveDenyToFavorite;
				}
				favoriteAsynkTask task = new favoriteAsynkTask();
				String[] params = new String[]{ url, "user_id", user_id,
									"deny_id", Preferences.getValue(getBaseContext(), "deny_id"),
									"favorite_id", Preferences.getValue(getBaseContext(), "favorite_id"),
									"user_id_check", Preferences.getValue(getBaseContext(), "user_id"),
									"uuid_check", Preferences.getValue(getBaseContext(), "uuid")};
				task.execute(params);
			}
		});
		board.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityGroup parentActivity = (ActivityGroup) getParent();
				Intent intent = new Intent(getBaseContext(), ProfileBoardActivity.class);
				intent.putExtra("user_id", user_id);
				intent.putExtra("check", check);
				((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("ProfileBoard", intent);
			}
		});
	}
	
	private class StationItemAdapter extends ArrayAdapter<StationItem>{
		private ArrayList<StationItem> items;
		private int layout;
		
		public StationItemAdapter(Context ctx, int rsrcId, ArrayList<StationItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			StationItem e = items.get(position);
			if(e != null){
				((TextView)v.findViewById(R.id.label)).setText(e.getStationName());
				((ImageView)v.findViewById(R.id.icon)).setImageResource(e.getIconId());
			}
			return v;
		}
	}
	
	public class StationItem{
		private String stationId, stationName;
		private int iconId;
		
		public StationItem(String initId, String initName){
			stationId = initId;
			stationName = initName;
			iconId = R.drawable.btn_add;
		}

		public String getStationId() {
			return stationId;
		}
		
		public String getStationName() {
			return stationName;
		}
		
		public int getIconId() {
			return iconId;
		}

		public void setIconId(int iconId) {
			this.iconId = iconId;
		}
		
	}
}
